package com.clouddot.baipai.ui.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.clouddot.baipai.R;
import com.clouddot.baipai.infrastructure.environment.Env;
import com.clouddot.baipai.infrastructure.environment.Environment;
import com.clouddot.baipai.model.beam.getArcticById.getArcticByIdResponse;
import com.clouddot.baipai.model.beam.getArcticList.ariticInfo;
import com.clouddot.baipai.model.beam.getArcticList.getArcticListResponse;
import com.clouddot.baipai.model.beam.getClassType.getClassTypeResponse;
import com.clouddot.baipai.ui.adapter.A_UrgentAdapter;
import com.clouddot.baipai.ui.util.ToastUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by wxy on 2018/5/22.
 */

public class A_UrgentActivity extends BaseActivity implements ViewPager.OnPageChangeListener,View.OnTouchListener{
    private ViewPager viewPager;
    private LinearLayout mBottomLiner;
    private  ImageView[] mBottomImages;
    private A_UrgentAdapter myPagerAdapter;
    private Thread mthread;
    private RelativeLayout relativeLayout;
    private Animation loadingAnim;

    private List<ariticInfo> list = new ArrayList<>();
    private List<getArcticByIdResponse> linearLayouts = new ArrayList<>();

    private boolean isLockSet = false;
    private boolean isLock = true;
    private View view;
    private ModleThread modleThread;

    private boolean isActivity = false; //当前有没有离开activity

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFormat(PixelFormat.TRANSLUCENT);
        Environment.getInstance().activities.add(this);

        runThreadAction("JJTZ"); //获取信息


        modleThread = new ModleThread();
        modleThread.start();
    }

    @Override
    protected void setContentView() {
        super.setContentView();
        if(Environment.getInstance().Height <= 100){
            setContentView(R.layout.h_a_urgent);
        }else{
            setContentView(R.layout.v_a_urgent);
        }
    }

    @Override
    protected void initControls() {
        super.initControls();
        viewPager = find(R.id.live_view_pager);
        mBottomLiner = find(R.id.live_indicator);
        relativeLayout = find(R.id.loading);
        ImageView loading = find(R.id.imgloading);

        loadingAnim = AnimationUtils.loadAnimation(this,R.anim.rotate);
        LinearInterpolator lir = new LinearInterpolator();
        loadingAnim.setInterpolator(lir);
        loading.startAnimation(loadingAnim);
        view = getWindow().getDecorView();

    }



    @Override
    protected void loadParams() {
        super.loadParams();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mhandler.sendEmptyMessage(H_SMainActivity.MSG_THREE);
        isActivity = false;


    }

    @Override
    protected void onPause() {
        super.onPause();
        isActivity = true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(modleThread != null)  modleThread.stopRun();
    }

    @Override
    protected void setListener() {
        super.setListener();
        viewPager.setOnTouchListener(this);
        viewPager.setOnPageChangeListener(this);
        view.setOnSystemUiVisibilityChangeListener
                (new View.OnSystemUiVisibilityChangeListener() {
                    @Override
                    public void onSystemUiVisibilityChange(int visibility) {
                        if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {
                            if(!isLockSet){
                                mhandler.sendEmptyMessage(H_SMainActivity.MSG_THREE);
                            }
                        } else {
                        }
                    }
                });
    }

    @Override
    protected void onStop() {
        super.onStop();
        isActivity = true;
    }

    @Override
    public void runThreadAction(String actionName) {
        super.runThreadAction(actionName);
    }

    @Override
    protected Object runThreadActionExceute(String actionName) {
        super.runThreadActionExceute(actionName);
        if(actionName.equals("JJTZ")){
            return Env.getAppPresenter().getArcticList(actionName,1,Env.getAppContext().itemCount);
        }else if(actionName.matches("[0-9]+")) {
            return Env.getAppPresenter().getArcticById(list.get(++currentViewPagerItem).getId());
        }
        return null;
    }

    @Override
    protected void runThreadActionSuccess(String actionName, Object result) {
        super.runThreadActionSuccess(actionName, result);
        if(actionName.matches("[0-9]+")) {
            getArcticByIdResponse response = (getArcticByIdResponse) result;
            if (response.isSuccess()) {
                linearLayouts.add(response);
                if(linearLayouts.size() == list.size()){
                    relativeLayout.setVisibility(View.GONE);
                    myPagerAdapter = new A_UrgentAdapter(linearLayouts,this);
                    viewPager.setAdapter(myPagerAdapter);
                    startAutoPlay();
                    creatCriclePoint();
                }
            } else {
                ToastUtil.showToast(this, response.getErrMsg());
            }
        } else if (actionName.equals("JJTZ")) {
            getArcticListResponse response = (getArcticListResponse) result;
            if (response.isSuccess()) {
                if (!response.list.isEmpty()) {
                    list = response.list;
                    linearLayouts.clear();
                    if(!list.isEmpty())
                        for (ariticInfo infoItem :list)
                            runThreadAction(infoItem.getId());
                }
            } else {
                ToastUtil.showToast(this, response.getErrMsg());
            }
        }

    }

    @Override
    protected void runThreadActionError(String actionName, Exception ex) {
        super.runThreadActionError(actionName, ex);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        currentViewPagerItem = position;
        if (linearLayouts != null) {
            position %= mBottomImages.length;
            int total = mBottomImages.length;

            for (int i = 0; i < total; i++) {
                if (i == position) {
                    mBottomImages[i].setImageResource(R.drawable.indicator_select);
                } else {
                    mBottomImages[i].setImageResource(R.drawable.indicator_no_select);
                }
            }
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        int action = motionEvent.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                isAutoPlay = false;
                break;
            case MotionEvent.ACTION_UP:
                isAutoPlay = true;
                break;
        }
        return false;
    }

    /***
     * 自动切换view
     */
    private void startAutoPlay() {
        if(mthread == null){
            //定时发送消息
            mthread = new Thread(){
                @Override
                public void run() {
                    super.run();
                    while (true) {
                        mhandler.sendEmptyMessage(H_SMainActivity.MSG_ONE);
                        try {
                            Thread.sleep(20000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            };
            mthread.start();
        }

    }

    private void creatCriclePoint() {
        mBottomImages = new ImageView[list.size()];
        for (int i = 0; i < mBottomImages.length; i++) {
            ImageView imageView = new ImageView(this);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(20, 20);
            params.setMargins(5, 0, 5, 0);
            imageView.setLayoutParams(params);
            if (i == 0) {
                imageView.setImageResource(R.drawable.indicator_select);
            } else {
                imageView.setImageResource(R.drawable.indicator_no_select);
            }
            mBottomImages[i] = imageView;
            mBottomLiner.addView(imageView);
        }
    }

    private int currentViewPagerItem = -1;
    private boolean isAutoPlay = true;
    @SuppressLint("HandlerLeak")
    private Handler mhandler = new Handler() {
        @SuppressLint("SetTextI18n")
        @Override
        public void handleMessage(final Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case H_SMainActivity.MSG_ONE:
                    if (isAutoPlay) {
                        ++currentViewPagerItem;
                        currentViewPagerItem =  currentViewPagerItem % list.size();
                        viewPager.setCurrentItem(currentViewPagerItem);
                    }
                    break;

                case H_SMainActivity.MSG_THREE:
                    isLockSet = true;
                    if (isLock) {
                        int uiFlags = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE;
                        getWindow().getDecorView().setSystemUiVisibility(uiFlags);
                    } else {
                        int uiFlags = View.SYSTEM_UI_FLAG_VISIBLE;
                        getWindow().getDecorView().setSystemUiVisibility(uiFlags);
                    }
                    isLockSet = false;
                    break;
            }
        }
    };
    private boolean flag = true;
    private class ModleThread extends Thread {

        private boolean stopFlag = false;
        @Override
        public void run() {
            do {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (!isActivity) {
                    getClassTypeResponse response = Env.getAppPresenter().getClassType();
                    if (response.isSuccess()) {

                        if (!response.Value.equals("Urgent")) {
                            flag = false;
                            Env.getAppContext().type = response.Value;
                            Env.getAppContext().DevicePath = response.DevicePath;
                            Intent i = new Intent(A_UrgentActivity.this, A_LaunchActivity.class);
                            A_UrgentActivity.this.startActivity(i);
                        }
                    }
                }
            } while (flag && !isActivity && !stopFlag);
        }
        private void stopRun() {
            stopFlag = true;
        }
    };

}
